﻿/**
 * 
 * Copyright 2009 Mike Jamer [email: mikejamer@gmail.com ]
 * 
 * This File is part of Moose IRC
 * 
 * MooseIRC is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * MooseIRC is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with MooseIRC.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace moose.irc
{
    /// <summary>
    /// Wrapps Socket, suitable for IRC Session
    /// </summary>
    [CLSCompliant(true)]
    public sealed class IrcConnection : object, IDisposable
    {
        /// <summary>
        /// Connection to IRC Server
        /// </summary>
        private Socket _socket;

        /// <summary>
        /// Used to buffer incomming responses
        /// </summary>
        private StringBuilder _response_buffer;

        /// <summary>
        /// Initialize IrcConnection
        /// </summary>
        internal IrcConnection()
            : base()
        {
            return;
        }

        /// <summary>
        /// Indicates whethere we're connected to teh server or not
        /// </summary>
        public bool Connected
        {
            get
            {
                return _socket.Connected;
            }
        }

        /// <summary>
        /// Signal Indicating a response from the server
        /// </summary>
        public event ResponseHandler Response;

        /// <summary>
        /// Connect socket to the IRC server
        /// </summary>
        /// <param name="host">host address of server</param>
        /// <param name="port">port number to connect to</param>
        /// <returns>true if connection was successful</returns>
        public bool connect(string host, int port)
        {
            if (_socket != null)
                disconnect();
            _socket = utility.NetworkUtility.createTcpSocket();
            _socket.Connect(utility.NetworkUtility.resolve(host), port);
            if (_socket.Connected)
            {
                _response_buffer = new StringBuilder();
                recieve();
            }
            return _socket.Connected;
        }

        /// <summary>
        /// Disconnect from the server, point socket to null
        /// </summary>
        /// <returns>true if disconnect was successful</returns>
        public bool disconnect()
        {
            if (_socket != null)
            {
                if (_socket.Connected) 
                    _socket.Disconnect(false);
                _socket = null;
            }
            return _socket == null;
        }

        /// <summary>
        /// Send data to the server
        /// </summary>
        /// <param name="command">command to send to the server</param>
        public void send(string command)
        {
            byte[] sendBuffer = Settings.DEFAULT_ENCODING.GetBytes(command + "\r\n"); //Appending the \r\n so you dont have to
            _socket.BeginSend(sendBuffer, 0, sendBuffer.Length, SocketFlags.None, onSendComplete, sendBuffer);
            return;
        }

        /// <summary>
        /// Recieve data from the server
        /// </summary>
        private void recieve()
        {
            byte[] recieveBuffer = new byte[512];

            try
            {
                _socket.BeginReceive(recieveBuffer, 0, recieveBuffer.Length, SocketFlags.None, onRecvComplete, recieveBuffer);
            }
            catch (Exception)
            {
                disconnect();
                return;
            }
            return;
        }

        /// <summary>
        /// Async Send Complete, this doesnt do much.
        /// </summary>
        /// <param name="result">Async Results</param>
        private void onSendComplete(IAsyncResult result)
        {
            byte[] sendBuffer = (byte[])result.AsyncState;
            return;
        }

        /// <summary>
        /// Async Recieve Complete,
        /// This is a major driving method in this system.
        /// </summary>
        /// <param name="result">Async Result</param>
        private void onRecvComplete(IAsyncResult result)
        {
            int recv = 0;
            byte[] recieveBuffer = (byte[])result.AsyncState;
            try {
                recv = _socket.EndReceive(result);
            } catch(Exception) {
                disconnect();
                return;
            }
            if (recv == 0) return;

            _response_buffer.Append(
                Settings.DEFAULT_ENCODING.GetString(recieveBuffer, 0, recv));

            //encode input, and break it down into lines
            foreach (string line in processResponseBuffer())
                Response(line); //Notify Client of response

            recieve(); //Set up recieve again
            return;
        }

        /// <summary>
        /// Alternative Way of handling messages
        /// </summary>
        /// <returns>array of responses</returns>
        /// <remarks>
        /// Handling this is more of a cached way, because it seems that the server
        /// sends messages continuously, so there are times when messages will come through, that
        /// look like garbage
        /// </remarks>
        private string[] processResponseBuffer()
        {
            List<string> responses = new List<string>();
            while (_response_buffer.ToString().IndexOf("\r\n") != -1)
            {
                string buf = _response_buffer.ToString();
                responses.Add(buf.Substring(0, buf.IndexOf("\r\n")));
                _response_buffer.Remove(0, 
                    buf.Substring(0, buf.IndexOf("\r\n")
                    ).Length + 2); //Remove message, plus the CRLF pair
            }
            return responses.ToArray();
        }

        /// <summary>
        /// Internal Trigger Handler
        /// </summary>
        /// <param name="response">response from server</param>
        /// <remarks>
        /// This is primarily here, simply to avoid a null reference exception, in the unlikely event that 
        /// that this event is not being subscribed to.
        /// </remarks>
        private void onResponse(string response)
        {
            return;
        }

        #region IDisposable Members

        /// <summary>
        /// Dispose Pattern
        /// </summary>
        public void Dispose()
        {
            disconnect();

            return;
        }

        #endregion
    }
}
